package cn.tworice.blog.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 核心服务
 * 静态工具类
 * @author 二饭
 * @email 1786705138@qq.com
 */
@Service
@Slf4j
public class CoreService {

    /**
     * 返回访问的IP地址
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-real-ip");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 生成token
     * @param ipAddress token有效时间
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public static String getLoginTicket(String ipAddress){
        Long time=System.currentTimeMillis()+(1000*60*60*24);
        Date date = new Date();
        date.setTime(time);
        String token=JWT.create().withAudience(ipAddress).withExpiresAt(date)// 将IP地址存入token中
        .sign(Algorithm.HMAC256(ipAddress));// 设置密钥为IP地址

        return token;
    }
}
